using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using StaffWarsFm.Discovery;
using StaffWarsFm.Lib.Data;

namespace StaffWarsFm.Server
{
    public static class RadioServiceHost
    {

        private static ServiceHost radioServiceHost;
        private static ServicePublisher publisher;

        public static ServiceHost Radio
        {
            get { return radioServiceHost; }
            set { radioServiceHost = value; }
        }

        public static void StartRadioService(string hostName, User user)
        {
            var radioServiceUri = ServerAddressGenerator.GenerateServerAddress(hostName);
            var radioService = new ServiceHost(typeof(RadioService), radioServiceUri);

            radioService.Open();

            Radio = radioService;

            StartPublisher(user);
        }

        public static void StopRadioService()
        {
            StopPublisher();

            radioServiceHost.Close();

            radioServiceHost = null;
            publisher = null;
        }

        private static void StartPublisher(User user)
        {
            publisher = new ServicePublisher();

            var hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());
            var ip4Address = hostAddresses.First(a => a.AddressFamily == AddressFamily.InterNetwork);
            publisher.Start(ip4Address.ToString(), user);
        }

        private static void StopPublisher()
        {
            publisher.Stop();
            publisher = null;
        }

    }
}